import fs from "fs";
import got from "got";
import dayjs from "dayjs";
import { pay } from "../utils/pay.js";
import config from "../config.js";
import { coverPayLink } from "../utils/payLink.js";
import { Cookie, cookieJar } from "../utils/cookie.js";
import payUrlConfig from "./payUrl.js";
import { sleep } from "../utils/util.js";

const configCookies = config.cookie.split(";").map(Cookie.parse);

const url = "https://mclient.alipay.com";
const cookieStr = await cookieJar.getCookieString(url);
if (cookieStr) {
  console.log(`使用缓存cookie`);
} else {
  console.log(`cookie无缓存，使用config中cookie`);
  for (const cookie of configCookies) {
    await cookieJar.setCookie(cookie, url);
  }
}

const links = fs.readFileSync("./links.txt", "utf8");

const getDateTimeString = () => dayjs().format("YYYY-MM-DD HH:mm:ss");

export const UrlReg = new RegExp(
  `((http|ftp|https)://)((localhost)|([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?`,
  "gi",
);

const urls = links.match(UrlReg) || [];

for (const url of urls) {
  const u = new URL(url);
  const sign = u.searchParams.get("sign");
  let curLog = `${url},`;

  try {
    console.log(sign, "获取支付连接");
    const payFun = payUrlConfig[u.host] || payUrlConfig.default;
    const payData = await payFun(u);
    console.log("支付参数：", payData);
    curLog += `支付参数：${payData},`;
    const payUrl = await coverPayLink(payData.replaceAll("&amp;", "&"));
    // curLog += `支付地址：${payUrl},`;
    console.log("支付地址：", payUrl);
    await pay(payUrl, config.payPwd);
    curLog += `支付成功`;
    console.log("支付成功");
  } catch (e) {
    const errMsg = e.message;
    console.log(errMsg);
    curLog += `失败：${errMsg},`;
    await sleep(10 * 1000);
  } finally {
    fs.appendFileSync("./logs.txt", `[${getDateTimeString()}] ${curLog}\n`);
    if (
      curLog.includes("超时") ||
      curLog.includes("支付密码不正确")
      // || curLog.includes("验证码")
    ) {
      process.exit(1);
    }
  }
}

// const paySdk = `app_id=2018081761038755&amp;biz_content=%7B%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22timeout_express%22%3A%224m%22%2C%22total_amount%22%3A%2213.9%22%2C%22subject%22%3A%22%E5%8C%97%E4%BA%AC%E6%98%9F%E5%B7%B4%E5%85%8B%E5%92%96%E5%95%A1%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22%2C%22store_id%22%3A%2265121%22%2C%22out_trade_no%22%3A%2225040210391000058686%22%2C%22seller_id%22%3A%222088721766874578%22%7D&amp;timestamp=2025-04-02+10%3A39%3A12&amp;charset=utf-8&amp;notify_url=https%3A%2F%2Fups.starbucks.com.cn%2FonlinePay%2Fnotify%2F20002&amp;sign_type=RSA2&amp;method=alipay.trade.app.pay&amp;version=1.0&amp;sign=HYa5Lq9VHLRDFvfX1Fc6m1SvhV372tJpWAlwq193TNMrz5Q%2BpLTT%2BLuiL0QYjqNnsSuQOP1zR%2B%2BR0rkIyaxFwVACVFpGhrlv0raHNRVkx1Jb8TyhZjlEpcBiZogtIMt2tcxk0vfksuaCTHTM43lsCtqVY%2BfEKT5rw1ut1kAtJTMAUZNwu2dL4DSR9Q1YJurEVLNG2OgOhRgVdGO4irqZVAqMJktwarg6s%2B%2BC4EAkyCSpOa3MqpJ5449PBzm9bghZ9MEzQQsubAciNhAQh8cS6sSZm2pH1WZ7hztcT4rpcfqpVAtwgZuPpC5LU7kFOtcooXSjlby1JnbqJsL%2FmR3h9A%3D%3D`;
// const payUrl = await coverPayLink(paySdk.replaceAll("&amp;", "&"));
// await pay(payUrl, config.payPwd);
